package com.george.order.loadbalance;

import java.util.Arrays;
import java.util.List;

/**
 * @title: HashingLoadBalancer.java
 * @description: 负载均衡算法-哈希（Hashing）
 * @author: George.Dong
 * @date: 2024/5/31 9:53
 */
public class HashingLoadBalancer {
    private List<String> servers;

    public HashingLoadBalancer(List<String> servers) {
        this.servers = servers;
    }

    public String getServer(String clientIP) {
        int hash = clientIP.hashCode();
        // 哈希值对服务器数量取模，得到服务器索引
        int serverIndex = Math.abs(hash) % servers.size();
        return servers.get(serverIndex);
    }

    public static void main(String[] args) {
        List<String> servers = Arrays.asList("Server1", "Server2", "Server3");
        HashingLoadBalancer lb = new HashingLoadBalancer(servers);

        System.out.println("-----------不同ip访问------------------");
        // 用for循环模拟9个不同的IP访问
        for (int i = 1; i <= 9; i++) {
            String clientIp = "192.168.0.13" + i;
            System.out.println("Client IP: " + clientIp + " -> Server: " + lb.getServer(clientIp));
        }
        System.out.println("-----------相同ip访问------------------");
        // 用for循环模拟三个相同的IP访问
        for (int i = 1; i <= 3; i++) {
            String clientIp = "192.168.0.131";
            System.out.println("Client IP: " + clientIp + " -> Server: " + lb.getServer(clientIp));
        }
    }
}
